package dataGateway;

import java.sql.*;
import domainLogic.Item;


/**
 * @author  jungmins
 */
public class ItemTable {

	/**
	 * @uml.property  name="instance"
	 * @uml.associationEnd  
	 */
	private static ItemTable instance = new ItemTable();
	
	/**
	 * @return
	 * @uml.property  name="instance"
	 */
	public static ItemTable getInstance()
	{
		return instance;
	}
		
	public ItemTable() {  }
	
	private Connection getConnection() throws Exception {
		return ConnectionPool.getInstance().getConnection();
	} //getConnection()
	
	public boolean insertItem(Item item) {
		long startTime = System.currentTimeMillis();
		Connection conn = null;
		PreparedStatement pstmt = null;
		boolean ret = false;
		
		try {
			conn = getConnection();
			String sql = "insert into items(user_id, cat_id, name, description, startingprice, reserveprice,"+ 
                "buyoutprice, enddate, realenddate, endnotified, regdate, filename) "+
					"values(?,?,?,?,?,?,?,?,?,'N',CURRENT_TIMESTAMP,?)";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,item.getUserId()); 
			pstmt.setInt(2,item.getCatId());
			pstmt.setString(3,item.getName());
			pstmt.setString(4,item.getDescription());
			pstmt.setDouble(5,item.getStartingprice());			
			pstmt.setDouble(6,item.getReserveprice());			
			pstmt.setDouble(7,item.getBuyoutprice());			
			pstmt.setTimestamp(8,item.getEnddate());			
			pstmt.setTimestamp(9,item.getEnddate());		
			pstmt.setString(10,item.getFilename());				
			if(pstmt.executeUpdate()>0)
				ret = true;
			
		} catch(Exception ex) {
			ex.printStackTrace();
		} finally {
			if(pstmt != null) try { pstmt.close(); } catch(SQLException ex) { }		
			if(conn  != null) try {  conn.close(); } catch(SQLException ex) { }
		}
		System.out.println("insertItem: "+(System.currentTimeMillis()-startTime));
		
		return ret;
	} //insertMember

	public boolean updateItemRealenddate(int itemId, Timestamp newTimeStamp) {
		long startTime = System.currentTimeMillis();
		Connection conn = null;
		PreparedStatement pstmt = null;
		try {
			conn = getConnection();
			
			String sql = "update items set realenddate = ? where id = ?";
			pstmt = conn.prepareStatement(sql);

			pstmt.setTimestamp(1,newTimeStamp);
			pstmt.setInt(2,itemId); 
			
			pstmt.executeUpdate();
		} catch(Exception ex) {
			ex.printStackTrace();
		} finally {
			if(pstmt != null) try { pstmt.close(); } catch(SQLException ex) { }		
			if(conn  != null) try {  conn.close(); } catch(SQLException ex) { }
		}
		System.out.println("insertItem: "+(System.currentTimeMillis()-startTime));
		
		return true;
	} //insertMember

} //class
